import os, cv2, random
import numpy as np

def normalight(img):

    assert (img is not None)
    img = img.astype(np.float32)
    img = img / 255.0
    img = cv2.pow(img, 0.2)
    
    sigma1 = 0.5
    sigma2 = 2.0
    
    pro1 = cv2.GaussianBlur(img, (0,0), sigma1)
    pro2 = cv2.GaussianBlur(img, (0,0), sigma2)
    
    img = pro1 - pro2
    new_img = cv2.pow(np.abs(img), 0.1)
    img /= np.power(cv2.mean(new_img)[0], 10)
    new_img = np.abs(img)
    
    tau = 10
    alpha = 0.1
    new_img = cv2.min(tau, new_img)
    new_img = cv2.pow(new_img, alpha, new_img)
    img = img / np.power(cv2.mean(new_img)[0], 1/alpha) / tau
    img1 = cv2.exp(img)
    img2 = cv2.exp(0-img)
    img = img1 - img2
    img_ = img1 + img2
    img = img / (img_+1e-9)
    
    img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
    img = cv2.convertScaleAbs(img, 255)
    return img
    
if __name__ == "__main__":
    
    PATH = "/mnt/e/G00101-BookRecognition/G001/database/lib_imgs/"
    img_names = os.listdir(PATH)
    progress, finish = 0, len(img_names)
    for name in random.sample(img_names, 5):
    # for name in img_names:
        img = cv2.imread(PATH + name)
        img_norm = normalight(img)
        # cv2.imwrite("/mnt/e/G00101-BookRecognition/G001/database/lib_normImgs/{}.png".format(name), img_norm)
        cv2.imwrite("/mnt/e/G00101-BookRecognition/G001/database/{}.png".format(name), img_norm)
        progress +=1
        print("[" + int(100.0*(progress/finish))*"=" + ">>" + "{:.2%}".format(1.0*(progress/finish)) +
        int(100-100.0*(progress/finish))*" " + "]", end="\r")
        print("\nDown!")